/**
 * 文件上传
 * 初始化：
 * fileUpload.fn_upload_file("#uploadFile_pic", "jpg|png|jpeg|bmp|gif", 400*1024*1024);
 */
(function ($) {
    $(function () {
    	try {
    		$("#close_btn").click(function(){
        		window.close();
        	});
        	if(global.fileId>0){
        		fileUpload.fids.push(global.fileId);
        		$.get("/admin/document/filemess-"+global.fileId+".do",function(data){
        			$("#href-filename").attr("href",window.rootPath+"/admin/document/file-"+global.fileId+".do").html(data.remoteName);
        		},"json");
        	}
		} catch (e) {
		}
    });
})(jQuery);
window.onbeforeunload = function(){
	if(fileUpload.isDel){
		fileUpload.del("cancel");
	}
}; 
var fileUpload = {
	isDel : false,
	fids : new Array(),
	delFile : function(id){
		if(global.fileId=="" && fileUpload.fids.length>0){
			fileUpload.del("del");
			fileUpload.fids = new Array();
		}
		fileUpload.isDel = true;
		fileUpload.fids.push(id);
	},
	del : function(flag){
		if(fileUpload.fids.length<=0){
			return;
		}
		if(flag=="save"){
			if(fileUpload.fids.length>1  && global.fileId!="" ){
				fileUpload.fids = fileUpload.fids.slice(0,fileUpload.fids.length-1);
			}else{
				return;
			}
		}else if(flag=="cancel" && global.fileId!=""){
			if(fileUpload.fids.length>1){
				fileUpload.fids = fileUpload.fids.slice(1,fileUpload.fids.length);
			}else{
				return;
			}
		}
		$.post(window.basePath+"/document/del-"+fileUpload.fids+".do");
		fileUpload.fids = new Array();
	},
	delById : function(fid){
		$.post(window.basePath+"/document/del-"+fid+".do");
	},
	formatFileSize : function(bytes) {
	    if (typeof bytes !== 'number') {
	        return '';
	    }
	    if (bytes >= 1000000000) {
	        return (bytes / 1000000000).toFixed(2) + ' GB';
	    }
	    if (bytes >= 1000000) {
	        return (bytes / 1000000).toFixed(2) + ' MB';
	    }
	    return (bytes / 1000).toFixed(2) + ' KB';
	},
	fn_upload_file : function($id, extLimit, sizeLimit){
		var fileName= $($id).attr("name");
		var box = $($id + "_box");
		$($id).fileupload({
			dataType : "json",
			maxNumberOfFiles : 1,
			dataType : "json",
			maxFileSize : sizeLimit,
			acceptFileTypes: new RegExp("\.("+extLimit+")$", "i"), // /(\.|\/)(apk|ipa|jpg|png)$/i,
			autoUpload : false,
			add : function(e, data) {
				var option = $(this).fileupload("option");
				$.each(
					data.files,
					function(index, file) {
						if (!option.acceptFileTypes.test(file.name)) {
							asyncbox.tips("格式只能是："+extLimit+"！","error");
						} else if (option.maxFileSize < file.size) {
							asyncbox.tips("请上传小于"+(sizeLimit/1024/1024)+"M的文件！", "error");
						} else {
							box.show();
							box.find(".progress-info").show()
							box.find(".sucess-deal").hide()
							box.find(".state").html("等待上传");
							box.find(".size").html(fileUpload.formatFileSize(file.size));
							$($id).parent().parent().find(".input-file-size").val(file.size);
							data.submit();
						}
					});
			},
			progressall : function(e, data) {
				var progress = parseInt(data.loaded / data.total * 100, 10);
				box.find('.progress-bar').css('width', progress + '%');
				box.find(".state").html("" + progress + '%');
			},
			start : function(e) {
				box.find('.progress-bar').css('width', '0%');
				box.find(".state").html("" + '0%');
			},
			done : function(e, data) {
				if (data.result.r) {
					var uploadFile = eval("("+"data.result.d[0]."+fileName+")");
					box.find('.progress-bar').css('width', '100%');
					box.find(".state").html("上传完成");
					$($id).parent().parent().find(".input-file-id").val(uploadFile.fileId);
					
					$($id).parent().parent().find(".input-file-size").val(uploadFile.fileSize);
					
					box.hide();
					
					$("#href-filename").attr("href",window.rootPath+"/admin/document/file-"+uploadFile.fileId+".do").html(uploadFile.remoteName);
					fileUpload.delFile(uploadFile.fileId);
					try {$('.input-file-id').trigger("validate");} catch (e) {}
				} else {
					box.find(".state").html("上传失败");
				}
				asyncbox.tips(data.result.m, data.result.r ? 'success' : 'error');
			},
			fail : function(e, data) {
				box.find(".state").html("上传错误");
			}
		});
	}
};
